package com.source.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.source.sys.service.PopedomService;
import com.source.sys.service.UserRoleService;
import com.source.utils.CommonResult;
import com.source.utils.JwtUtils;
import com.source.utils.ResponseUtils;
import com.source.utils.ResultEnum;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * @Author ZZF
 * @Time 2021/04/01 21:15
 * @Desription 权限管理拦截器
 */
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {
    @Resource
    private PopedomService popedomService;
    @Resource
    private UserRoleService userRoleService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");

        //解决乱码问题
        ResponseUtils.solveEncoding(request, response);
        //获取token
        String token = request.getHeader("Authorization");
        //从token中获取权限信息
        JwtUtils jwtUtils = new JwtUtils();
        Claims claims = jwtUtils.parseJWT(token);
        String subject = claims.getSubject();
        HashMap hashMap = JSONObject.parseObject(subject, HashMap.class);
        //从数据库中获取角色id
        String userId = (String)hashMap.get("userId");
        String currentRoleId = userRoleService.getRoleIdByUserId(userId);
        //获取controller请求的requestMapping的uri
        //uri
        String requestMappingUri = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString();
        //pathVariable的key = value格式
        String uriTemplateVariablesAttribute = request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE).toString();
        //requestMapping的uri中的pathVarialbe转化为*
        if(uriTemplateVariablesAttribute.equals("{}") == false){
            //切割子串
            String substring = uriTemplateVariablesAttribute.substring(0, uriTemplateVariablesAttribute.indexOf('=')) + "}";
            requestMappingUri = requestMappingUri.replace(substring, "*");
        }
        //先获取请求方式，GET暂时全部放行，再获取请求的URI，如果该URI和数据库的对应上了，则放行，否则拦截请求方式
        String requestMethod = request.getMethod();
        if("GET".equals(requestMethod)){
            return true;
        }else{
            //如果是其他方式
            //检查请求方式和是否有访问该uri权限
            //有则放行，没有则拦截
            boolean checkPopedom = popedomService.checkUriAndMethodByRoleId(currentRoleId, requestMappingUri, requestMethod);
            if (checkPopedom == true){
                return true;
            }
        }
        ResponseUtils.write(response,new CommonResult(ResultEnum.NO_ACCESS));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
